package cc.edge2.sns.services;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.arnx.jsonic.JSON;
import cc.edge2.sns.commons.PMF;
import cc.edge2.sns.models.FriendRelation;
import cc.edge2.sns.models.SNSUser;

public class GetUserProfileService {
	public String execute(Map params, SNSUser loginUser) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> contents = new HashMap<String, Object>();
		Map<String, Object> status = new HashMap<String, Object>();
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		long userId = Integer.parseInt((String)params.get("userId"));
		SNSUser user = null;
		String friendStatus = null;
		if(userId == loginUser.getUserId()) {
			user = loginUser;
			friendStatus = "self";
		} else {
			try {
				user = pm.getObjectById(SNSUser.class, userId);
				user = pm.detachCopy(user);
				Query query = pm.newQuery(FriendRelation.class);
				try {
					query.setFilter("userId1 == :userId1Param && userId2 == :userId2Param");
					int size = ((List)query.execute(loginUser.getUserId(), user.getUserId())).size();
					if(size > 0) {
						friendStatus = "friend";
					} else {
						friendStatus = "other";
					}
				} finally {
					query.closeAll();
				}
			} catch(JDOObjectNotFoundException e) {
				e.printStackTrace();
				status.put("code", "404");
				status.put("message", "not found");
				result.put("status", status);
				String value = JSON.encode(result);
				return value;
			} finally {
				pm.close();
			}
		}
		
		
		status.put("code", "0");
		status.put("message", "success");
		contents.put("name", user.getName());
		contents.put("thumbnailUrl", user.getThumbnailUrl());
		contents.put("userId", user.getUserId());
		contents.put("currentUserId", user.getUserId());
		contents.put("selfIntroduction", user.getSelfIntroduction());
		contents.put("friendStatus", friendStatus);
		result.put("status", status);
		result.put("contents", contents);
		String value = JSON.encode(result);
		return value;
	}
}
